﻿using ClosedXML.Excel;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SmartProduction.Domain.yjh;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue;
using SmartProduction.Read.API.Application.Commands.GodProductPlan;
using SmartProduction.Read.API.Application.Commands.MaterList;
using SmartProduction.Read.API.Application.Commands.WareHouser;
using SmartProduction.Read.API.Application.Commands.WorkFlow;
using SmartProduction.Read.API.Application.Commands.WorkNum;

namespace SmartProduction.Read.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class MangerController : ControllerBase
    {
        /// <summary>
        /// 中介者
        /// </summary>
        private readonly IMediator mediator;
        private readonly DataDbContext db;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="mediator">中介者</param>
        public MangerController(IMediator mediator, ILogger<MangerController> logger,DataDbContext db)
        {
            this.mediator = mediator;
            this.db = db;
        }
        /// <summary>
        /// 条件查询物料列表
        /// </summary>
        /// <param name="request">实体</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回集合</returns>
        [HttpGet]
        public async Task<APIResult<APIPaing<MaterialList>>> QueryMaterList([FromQuery]MaterQueryListCommand request)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 物料类型查询列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<List<MaterialListType>>> QuearyMaterListType([FromQuery]MaterListTypeQueryCommad request)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 工作流查询
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<APIPaing<Workflows>>> QueryWorkFlow([FromQuery]WorkFlowQueryCommand request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 主生产计划查询
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<APIPaing<ProductPlan>>> QueryProduct([FromQuery]ProductPlanQueryCommand request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        ///仓库列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<APIPaing<WareHouse>>> QueryWareHouse([FromQuery]WareHouseQueryCommand request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 擦汗寻工序管理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<APIPaing<Process>>> QueryProcess([FromQuery]WorkNumQueryCommand request, CancellationToken cancellationToken)
        {
            return await mediator.Send(request);
        }


        [HttpGet]
        public async Task<IActionResult> ExportInventories()
        {
            try
            {
                // 从数据库中查询 ProductPlan 数据
                var productPlans = await db.ProductPlans.ToListAsync();

                if (productPlans == null || productPlans.Count == 0)
                {
                    return NotFound("没有找到要导出的数据。");
                }

                // 创建一个新的 Excel 工作簿
                using (var workbook = new XLWorkbook())
                {
                    var worksheet = workbook.Worksheets.Add("ProductPlans");

                    // 添加表头
                    worksheet.Cell(1, 1).Value = "计划代码";
                    worksheet.Cell(1, 2).Value = "计划名称";
                    worksheet.Cell(1, 3).Value = "计划描述";
                    worksheet.Cell(1, 4).Value = "制表人";
                    worksheet.Cell(1, 5).Value = "制表部门";
                    worksheet.Cell(1, 6).Value = "状态";
                    worksheet.Cell(1, 7).Value = "审批状态";
                    worksheet.Cell(1, 8).Value = "创建时间";
                    worksheet.Cell(1, 9).Value = "是否删除";

                    // 填充数据
                    for (int i = 0; i < productPlans.Count; i++)
                    {
                        var plan = productPlans[i];
                        worksheet.Cell(i + 2, 1).Value = plan.PlanCode;
                        worksheet.Cell(i + 2, 2).Value = plan.PlanName;
                        worksheet.Cell(i + 2, 3).Value = plan.PlanDes;
                        worksheet.Cell(i + 2, 4).Value = plan.MakeListPerson;
                        worksheet.Cell(i + 2, 5).Value = plan.MakeListDepart;
                        worksheet.Cell(i + 2, 6).Value = plan.IsStatus;
                        worksheet.Cell(i + 2, 7).Value = plan.ApproveStatus;
                        worksheet.Cell(i + 2, 8).Value = plan.CreateTime;
                        worksheet.Cell(i + 2, 9).Value = plan.IsDeleted;
                    }

                    // 将工作簿保存到 MemoryStream
                    using (var stream = new MemoryStream())
                    {
                        workbook.SaveAs(stream);
                        var content = stream.ToArray();

                        // 设置响应头
                        return File(
                            content,
                            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                            "ProductPlans.xlsx");
                    }
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"导出失败，原因：{ex.Message}");
            }
        }


    }
}
